package com.tencent.wxcloudrun.controller;

import cn.hutool.core.map.MapUtil;
import com.tencent.wxcloudrun.config.ApiResponse;
import com.tencent.wxcloudrun.controller.form.AddApplyRecordForm;
import com.tencent.wxcloudrun.model.ApplyRecord;
import com.tencent.wxcloudrun.model.Product;
import com.tencent.wxcloudrun.model.User;
import com.tencent.wxcloudrun.service.ApplyRecordService;
import com.tencent.wxcloudrun.service.ProductService;
import com.tencent.wxcloudrun.utils.JwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
import java.util.Optional;


@RestController
@RequestMapping("/apply")
public class ApplyRecordController {

    @Resource
    private ApplyRecordService applyRecordService;

    @Resource
    private ProductService productService;


    /**
     * 查询当前用户的申请记录
     */
    @GetMapping("/list")
    public ApiResponse getUserRecords(@RequestHeader("Authorization") String token) {
        // 解析 Token
        String mobile = JwtUtil.parseToken(token);
        if (mobile == null) {
            return ApiResponse.authError("用户未登录，请重新登录");
        }
        return ApiResponse.ok(applyRecordService.getUserRecordsByMobile(mobile));
    }

    /**
     * 提交申请
     */
    @PostMapping("/add")
    public ApiResponse createApplyRecord(@RequestHeader("Authorization") String token, @RequestBody @Valid AddApplyRecordForm request) {
        String mobile = JwtUtil.parseToken(token);
        if (mobile == null) {
            return ApiResponse.authError("用户未登录，请重新登录");
        }
        User user = applyRecordService.getUserByMobile(mobile);
        if (null == user) {
            return ApiResponse.authError("用户未找到，请重新登录");
        }
        // 查询产品
        Optional<Product> productOptional = productService.getProductById(request.getProductId());
        if (!productOptional.isPresent()) {
            return ApiResponse.error("产品不存在");
        }
        // 创建申请记录
        ApplyRecord applyRecord = AddApplyRecordForm.buildModelByForm(request, user, productOptional.get());
        // 保存到数据库
        applyRecordService.save(applyRecord);

        return ApiResponse.ok("申请提交成功");
    }

    /**
     * 更新申请
     */
    @PutMapping("/update")
    public ApiResponse updateApplyRecord(@RequestHeader("Authorization") String token, @RequestBody ApplyRecord record) {
        String username = JwtUtil.parseToken(token);
        if (username == null) {
            return ApiResponse.authError("用户未登录，请重新登录");
        }
        return ApiResponse.ok(applyRecordService.save(record));
    }

    /**
     * 逻辑删除申请
     */
    @DeleteMapping("/delete/{id}")
    public ApiResponse deleteApplyRecord(@RequestHeader("Authorization") String token, @PathVariable Long id) {
        String username = JwtUtil.parseToken(token);
        if (username == null) {
            return ApiResponse.authError("用户未登录，请重新登录");
        }
        applyRecordService.deleteById(id);
        return ApiResponse.ok("删除成功（逻辑删除）");
    }


    @PostMapping("/confirm")
    public ApiResponse confirmApplyRecord(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> params) {
        try {
            Long id = MapUtil.getLong(params, "id");
            String mobile = JwtUtil.parseToken(token);
            if (mobile == null) {
                return ApiResponse.authError("用户未登录，请重新登录");
            }
            User user = applyRecordService.getUserByMobile(mobile);
            if (null == user) {
                return ApiResponse.authError("用户未找到，请重新登录");
            }
            if (null == id) {
                return ApiResponse.authError("没有找到记录id");
            }
            applyRecordService.confirmApplyRecord(id);
            return ApiResponse.ok("确认成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

}
